package com.unibuy.smartdevice.ui.devs.flower;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.controller.DevFlowerController;
import com.unibuy.smartdevice.database.SlotsDao;
import com.unibuy.smartdevice.databinding.ActivityFlowerSlotListBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSecurityException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.devs.electric.ElectricSlotListActivity;

public class FlowerSlotListActivity extends AppCompatActivityAbstract {
    private @NonNull ActivityFlowerSlotListBinding binding;
    private ActivityResultLauncher<Intent> resultLauncher;
    private RecyclerFlowerSlotListAdpter recyclerFlowerSlotListAdpter;
    private HttpAPI httpAPI;
    private static int slotcount;

    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityFlowerSlotListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        httpAPI = new HttpAPI(getHandlerMain());
        slotcount = 10 ;
        resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult o) {
                    if (o.getResultCode() == RESULT_OK && o.getData() != null) {
                        int position = o.getData().getIntExtra("position", 0);
                        int slot = MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).get(position).getSlot();
                        String productId = o.getData().getStringExtra("product_id");
                        getLogs().info("接收到回傳值:" + position + "," + slot + "," + productId);
                        for(ProductStructure product: MyApp.getInstance().getProductList()) {
                            if (product.getProductID().equals(productId)) {
                                MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).set(position, new SlotStructure(SlotField.FLOWER.getField(), slot, product, 0));
                                break;
                            }
                        }
                        recyclerFlowerSlotListAdpter.notifyItemChanged(position);
                    }
                }
            }
        );

//        MyApplication.getInstance().initialSlotData();

        recyclerFlowerSlotListAdpter = new RecyclerFlowerSlotListAdpter(this, resultLauncher, MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()));
        binding.recyclerSlotList.setAdapter(recyclerFlowerSlotListAdpter);
        binding.recyclerSlotList.setLayoutManager(new LinearLayoutManager(this));

//        dataShow();

        binding.buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                updateSlotListNum();
                finish();
            }
        });

        binding.buttonReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearData();
                saveData();
                dataShow();
            }
        });


        binding.buttonGotoElectricSlotList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                gotoElectricAcitvity();
            }
        });

        binding.buttonAllOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    allOpen();
                } catch (LogsSecurityException e) {
                    throw new RuntimeException(e);
                } catch (LogsUnsupportedOperationException e) {
                    throw new RuntimeException(e);
                } catch (LogsIOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        if (MyApp.getInstance().getDevSet().isElectic()) {
            binding.buttonGotoElectricSlotList.setVisibility(View.VISIBLE);
        } else {
            binding.buttonGotoElectricSlotList.setVisibility(View.GONE);
        }
    }

    public void gotoElectricAcitvity() {
        startActivity(new Intent(this, ElectricSlotListActivity.class));
        finish();
    }

    private void allOpen() throws LogsSecurityException, LogsUnsupportedOperationException, LogsIOException {
        getLogs().info("鮮花機，一鍵全開按鈕");
        DevFlowerController devFlowerController = new DevFlowerController(setHandlerMain());
        for(int i = 1 ; i <= 10 ; i++) {
            devFlowerController.devSendCustomCommand(i);
            devFlowerController.start();
        }
    }

    private void saveData() {
        SlotsDao slotsDao = new SlotsDao(this);
        slotsDao.deleteAll();
        slotsDao.insertAll(MyApp.getInstance().getSlotMap());
        slotsDao.close();
        getLogs().info("save count:"+ MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).size());
    }

    public void clearData() {
        SlotsDao slotsDao = new SlotsDao(this);
        slotsDao.deleteAll();
        slotsDao.close();
        int slotListSize = MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).size();
        MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).clear();
        if (slotListSize > 0) {
            recyclerFlowerSlotListAdpter.notifyItemRangeRemoved(0, slotListSize);
        }
        if (MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).isEmpty()) {
            for (int i = 1; i <= slotcount; i++) {
                MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).add(new SlotStructure(SlotField.FLOWER.getField(), i,
                        new ProductStructure("?", "", "", 0, 0, 0, 0, "", "","",""),
                        0));
            }
            getLogs().info(SlotField.FLOWER.getField() + " count:"+ MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).size());
        }
    }

    private void testData() {
        for(int i=1;i<=slotcount;i++) {
            MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).add(new SlotStructure(SlotField.FLOWER.getField(), i,
                new ProductStructure(
                "1000",
                "gg1.png",
                "測試小精靈"+i,
                100+1,
                100+2,
                100+3,
                8,
                        "",
                        "",
                        "",
                        ""
                ), 3));
        }
    }

    public void dataShow() {
        getLogs().info("recycler data count:"+this.recyclerFlowerSlotListAdpter.getItemCount());
        recyclerFlowerSlotListAdpter.notifyItemInserted(MyApp.getInstance().getSlotList(SlotField.FLOWER.getField()).size() -1);
    }

    public void updateSlotListNum(){
        try {
            MyApp.getInstance().getReportSlotListStructure().setAccount(MyApp.getInstance().getSuAccess());
            MyApp.getInstance().getReportSlotListStructure().setVmctype("U4");
            httpAPI.reportSlotList(MyApp.getInstance().getReportSlotListStructure());
        } catch (LogsParseException e) {
            throw new RuntimeException(e);
        } catch (LogsSettingEmptyException e) {
            throw new RuntimeException(e);
        }
    }
}